package com.IC.base.service.impl;


import IC.common.core.domain.R;
import IC.common.core.utils.bean.BeanUtils;
import IC.common.core.utils.file.FileTypeUtils;
import com.IC.base.mapper.ActualPopulationMapper;
import com.IC.base.mapper.ActualPopulationTagMapper;
import com.IC.base.mapper.ActualTenementMapper;
import com.IC.base.service.ActualPopulationService;
import com.IC.domain.PersonnelType;
import com.alibaba.nacos.common.utils.IoUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.IC.domain.dto.ActualPopulationDTO;
import com.IC.domain.po.ActualPopulationPo;
import com.IC.domain.po.NationPO;
import com.IC.domain.vo.ActualPopulationVO;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Service
public class ActualPopulationServiceImpl extends ServiceImpl<ActualPopulationMapper, ActualPopulationPo> implements ActualPopulationService {

    @Autowired
    private ActualPopulationMapper actualPopulationMapper;
    @Autowired
    private ActualPopulationTagMapper actualPopulationTagMapper;
    @Autowired
    private ActualTenementMapper actualTenementMapper;

    /**
     * 域名或本机访问地址
     */
    @Value("${fdfs.domain}")
    public String domain;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    /**
     * 查询实有人口信息
     * @param actualPopulationDTO
     * @return
     */
    @Override
    public PageInfo<ActualPopulationVO> findlist(ActualPopulationDTO actualPopulationDTO) {
        PageHelper.startPage(actualPopulationDTO.getPageNum(), actualPopulationDTO.getPageSize());
        //查询实有人口和民族信息
        List<ActualPopulationVO> list=actualPopulationMapper.findPopulationlist(actualPopulationDTO);
        for (ActualPopulationVO actualPopulationVO : list) {
            //查询住户信息
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                ActualPopulationVO actualPopulationVO1 = actualTenementMapper.findByPopulationId(actualPopulationVO.getId());
                actualPopulationVO.setDivisionId(actualPopulationVO1.getDivisionId());
                actualPopulationVO.setDivisionName(actualPopulationVO1.getDivisionName());
                actualPopulationVO.setBuildingName(actualPopulationVO1.getBuildingName());
                actualPopulationVO.setApartmentName(actualPopulationVO1.getApartmentName());
                actualPopulationVO.setPlotName(actualPopulationVO1.getPlotName());
                actualPopulationVO.setTenementName(actualPopulationVO1.getTenementName());
            });
            //查询用户身份标签
            CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
                ActualPopulationVO actualPopulationVO2 = actualPopulationTagMapper.findByPopulationId(actualPopulationVO.getId());
                if(actualPopulationVO2!=null){
                    actualPopulationVO.setPopulationTagIds(actualPopulationVO2.getPopulationTagIds());
                    actualPopulationVO.setPopulationTagName(actualPopulationVO2.getPopulationTagName());
                }
            });
            CompletableFuture.allOf(voidCompletableFuture, voidCompletableFuture1).join();
        }
        PageInfo<ActualPopulationVO> actualPopulationVOPageInfo = new PageInfo<>(list);
        return actualPopulationVOPageInfo;
    }

    /**
     * 查询民族信息
     * @return
     */
    @Override
    public List<NationPO> findNationList() {
        List<NationPO> nationList = actualPopulationMapper.findNationList();
        return nationList;
    }

    /**
     * 查询所有实有人口信息下拉框
     * @return
     */
    @Override
    public List<ActualPopulationPo> findAll() {
        List<ActualPopulationPo> all = actualPopulationMapper.findAll();
        return all;
    }

    @Override
    public List<ActualPopulationPo> selectlist() {
        return actualPopulationMapper.selectlist();
    }

    /**
     * 导入
     * @param actualPopulationPos
     */
    @Override
    public void insertList(List<ActualPopulationPo> actualPopulationPos) {
        actualPopulationMapper.insertList(actualPopulationPos);
    }

    /**
     * 根据地块ID查询人口实际入住信息
     *
     * @param id 小区ID
     * @param pageNum 页码
     * @param pageSize 每页显示的条数
     * @return 返回人口实际入住信息的分页数据
     */
    @Override
    public PageInfo<ActualPopulationVO> findByPlotId(Integer id, Integer pageNum, Integer pageSize) {
        // 开始分页
        PageHelper.startPage(pageNum, pageSize);
        // 创建查询条件对象
        ActualPopulationDTO actualPopulationDTO = new ActualPopulationDTO();
        // 设置小区ID作为查询条件
        actualPopulationDTO.setPlotId(id);
        // 调用Mapper查询人口实际入住列表
        List<ActualPopulationVO> list=actualPopulationMapper.findPopulationlist(actualPopulationDTO);
        // 遍历查询结果，补充住户信息和身份标签
        for (ActualPopulationVO actualPopulationVO : list) {
            // 异步查询住户信息
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                // 通过人口ID查询详细的住户信息
                ActualPopulationVO actualPopulationVO1 = actualTenementMapper.findByPopulationId(actualPopulationVO.getId());
                // 补充住户信息到结果集
                actualPopulationVO.setDivisionId(actualPopulationVO1.getDivisionId());
                actualPopulationVO.setDivisionName(actualPopulationVO1.getDivisionName());
                actualPopulationVO.setBuildingName(actualPopulationVO1.getBuildingName());
                actualPopulationVO.setApartmentName(actualPopulationVO1.getApartmentName());
                actualPopulationVO.setPlotName(actualPopulationVO1.getPlotName());
            });
            // 异步查询用户身份标签
            CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
                // 通过人口ID查询身份标签信息
                ActualPopulationVO actualPopulationVO2 = actualPopulationTagMapper.findByPopulationId(actualPopulationVO.getId());
                // 补充身份标签信息到结果集
                actualPopulationVO.setPopulationTagIds(actualPopulationVO2.getPopulationTagIds());
                actualPopulationVO.setPopulationTagName(actualPopulationVO2.getPopulationTagName());
            });
            // 等待所有异步任务完成
            CompletableFuture.allOf(voidCompletableFuture, voidCompletableFuture1).join();
        }
        // 创建并返回分页信息对象
        PageInfo<ActualPopulationVO> actualPopulationVOPageInfo = new PageInfo<>(list);
        return actualPopulationVOPageInfo;
    }

    @Override
    public String findcount() {
        return actualPopulationMapper.findcount();
    }

    /**
     * 根据小区ID列表查询实际人口信息
     *
     * @param id 地块ID
     * @return 实际人口信息列表
     */
    @Override
    public List<ActualPopulationVO> findByPlotIdList(Integer id) {
        // 创建实际人口DTO对象，设置地块ID
        ActualPopulationDTO actualPopulationDTO = new ActualPopulationDTO();
        actualPopulationDTO.setPlotId(id);

        // 通过小区ID查询实际人口信息列表
        List<ActualPopulationVO> list = actualPopulationMapper.findPopulationlist(actualPopulationDTO);

        // 遍历实际人口信息列表，异步查询住户信息和用户身份标签
        for (ActualPopulationVO actualPopulationVO : list) {
            // 异步查询住户信息
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                // 通过实际人口ID查询住户信息，并更新实际人口对象的住户信息字段
                ActualPopulationVO actualPopulationVO1 = actualTenementMapper.findByPopulationId(actualPopulationVO.getId());
                actualPopulationVO.setDivisionId(actualPopulationVO1.getDivisionId());
                actualPopulationVO.setDivisionName(actualPopulationVO1.getDivisionName());
                actualPopulationVO.setBuildingName(actualPopulationVO1.getBuildingName());
                actualPopulationVO.setApartmentName(actualPopulationVO1.getApartmentName());
                actualPopulationVO.setTenementName(actualPopulationVO1.getTenementName());
                actualPopulationVO.setPlotName(actualPopulationVO1.getPlotName());
            });

            // 异步查询用户身份标签
            CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
                // 通过实际人口ID查询用户身份标签，并更新实际人口对象的身份标签字段
                ActualPopulationVO actualPopulationVO2 = actualPopulationTagMapper.findByPopulationId(actualPopulationVO.getId());
                if(actualPopulationVO2!=null){
                    actualPopulationVO.setPopulationTagIds(actualPopulationVO2.getPopulationTagIds());
                    actualPopulationVO.setPopulationTagName(actualPopulationVO2.getPopulationTagName());
                }
            });
            // 等待异步任务全部完成
            CompletableFuture.allOf(voidCompletableFuture, voidCompletableFuture1).join();
        }

        // 返回实际人口信息列表
        return list;
    }

    @Override
    public void dotransfer(ActualPopulationVO actualPopulationVO) {
        actualPopulationMapper.dotransfer(actualPopulationVO);
    }


    @Override
    @Transactional
    public R add(ActualPopulationVO actualPopulationVO) {
        List<ActualPopulationPo> actualPopulationPos= actualPopulationMapper.findIdNum();
        for (ActualPopulationPo actualPopulationPo : actualPopulationPos) {
            if(actualPopulationPo.getIdNumber().equals(actualPopulationVO.getIdNumber())){
                return R.ok("身份证号已存在");
            }
        }
        // 创建一个新的实际人口数据实体对象
        ActualPopulationPo actualPopulationPo = new ActualPopulationPo();
        // 将实际人口数据视图对象的属性复制到实体对象
        BeanUtils.copyBeanProp(actualPopulationPo, actualPopulationVO);
        // 插入实际人口数据到数据库
        actualPopulationMapper.insert(actualPopulationPo);
        // 获取实际人口数据关联的人口标签ID列表
        List<Integer> populationTagId = actualPopulationVO.getPopulationTagId();
        // 遍历人口标签ID列表，将每个标签与实际人口数据关联
        for (Integer tagId : populationTagId) {
            actualPopulationTagMapper.add(actualPopulationPo.getId(),tagId);
        }
        return R.ok("添加成功");
    }

    @Override
    public void updateByPoId(ActualPopulationVO actualPopulationVO) {
        // 创建一个实际人口数据实体类对象
        ActualPopulationPo actualPopulationPo = new ActualPopulationPo();
        // 使用BeanUtils工具类将实际人口数据对象的属性复制到实际人口数据实体类对象中
        BeanUtils.copyBeanProp(actualPopulationPo, actualPopulationVO);
        // 更新实际人口数据实体类对象
        actualPopulationMapper.updateById(actualPopulationPo);
        // 删除与实际人口数据实体类对象关联的人口标签数据
        actualPopulationMapper.deleteByPoId(actualPopulationPo.getId());
        // 获取实际人口数据对象中的人口标签ID列表
        List<Integer> populationTagId = actualPopulationVO.getPopulationTagId();
        // 遍历人口标签ID列表
        for (Integer tagId : populationTagId) {
            // 为实际人口数据对象添加新的标签关联
            actualPopulationTagMapper.add(actualPopulationVO.getId(),tagId);
        }
    }

    @Override
    public ActualPopulationVO findById(Integer id) {
        ActualPopulationVO byId = actualPopulationMapper.findById(id);
        return byId;
    }

    @Override
    public List<ActualPopulationVO> findByTenementId(Integer id) {
        return actualPopulationMapper.findByTenementId(id);
    }

    @Override
    @Transactional
    public List<ActualPopulationVO> all() {
        List<ActualPopulationVO> list=actualPopulationMapper.findPopulationlist(null);
        for (ActualPopulationVO actualPopulationVO : list) {
            //查询住户信息
            CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
                ActualPopulationVO actualPopulationVO1 = actualTenementMapper.findByPopulationId(actualPopulationVO.getId());
                actualPopulationVO.setDivisionId(actualPopulationVO1.getDivisionId());
                actualPopulationVO.setDivisionName(actualPopulationVO1.getDivisionName());
                actualPopulationVO.setBuildingName(actualPopulationVO1.getBuildingName());
                actualPopulationVO.setApartmentName(actualPopulationVO1.getApartmentName());
                actualPopulationVO.setPlotName(actualPopulationVO1.getPlotName());
            });
            //查询用户身份标签
            CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
                ActualPopulationVO actualPopulationVO2 = actualPopulationTagMapper.findByPopulationId(actualPopulationVO.getId());
                actualPopulationVO.setPopulationTagIds(actualPopulationVO2.getPopulationTagIds());
                actualPopulationVO.setPopulationTagName(actualPopulationVO2.getPopulationTagName());
            });
            CompletableFuture.allOf(voidCompletableFuture, voidCompletableFuture1).join();
        }
        kafkaTemplate.send("Population", list);
        return list;
    }

    @Override
    public String upload(MultipartFile file) {
        try {
            InputStream inputStream = file.getInputStream();
            StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(),
                    FileTypeUtils.getExtension(file), null);
            IoUtils.closeQuietly(inputStream);
            return domain + "/" + storePath.getFullPath();
        }catch (Exception e){
            return "上传失败";
        }
    }

    @Override
    public Integer findCount() {
        return actualPopulationMapper.findAllcount();
    }

    @Override
    public Integer findTodayAddCount() {
        return actualPopulationMapper.findTodayAddCount();
    }

    @Override
    public List<ActualPopulationVO> findlasttime(ActualPopulationDTO actualPopulationDTO) {
        return actualPopulationMapper.findlasttime(actualPopulationDTO);
    }


    @Override
    public PersonnelType findPersonType() {
        return actualPopulationMapper.findPersonType();
    }

}
